// Use Electron IPC for real HTTP server or mock for development
let httpServer

if (window.require) {
  // Electron environment
  const { ipcRenderer } = window.require('electron')
  httpServer = {
    start: (config) => ipcRenderer.invoke('http-server:start', config),
    stop: () => ipcRenderer.invoke('http-server:stop'),
    addRoute: (route, response) => ipcRenderer.invoke('http-server:add-route', { route, response }),
    removeRoute: (route) => ipcRenderer.invoke('http-server:remove-route', route),
    onRequestLog: (callback) => {
      ipcRenderer.on('http-server:request-log', (event, log) => callback(log))
    }
  }
} else {
  // Browser development environment - create mock implementation
  httpServer = {
    start: async (config) => {
      console.log('Mock HTTP Server starting on port', config.port)
      return { success: true, message: `Mock server started on port ${config.port}` }
    },
    stop: async () => {
      console.log('Mock HTTP Server stopping')
      return { success: true, message: 'Mock server stopped' }
    },
    addRoute: async (route, response) => {
      console.log('Mock: Route added', route, response)
      return { success: true }
    },
    removeRoute: async (route) => {
      console.log('Mock: Route removed', route)
      return { success: true }
    },
    onRequestLog: (callback) => {
      console.log('Mock: Request log listener registered')
      // Simulate some requests for testing
      setTimeout(() => {
        callback({
          timestamp: new Date().toISOString(),
          method: 'GET',
          url: '/api/test',
          ip: '127.0.0.1',
          status: 200,
          responseTime: 123
        })
      }, 3000)
    }
  }
}

const state = {
  isRunning: false,
  port: 3000,
  routes: [],
  requestLogs: [],
  maxLogs: 1000
}

const mutations = {
  SET_RUNNING(state, running) {
    state.isRunning = running
  },
  
  SET_PORT(state, port) {
    state.port = port
  },
  
  ADD_ROUTE(state, route) {
    state.routes.push({
      ...route,
      id: `route_${Date.now()}`,
      enabled: true
    })
  },
  
  UPDATE_ROUTE(state, { id, data }) {
    const index = state.routes.findIndex(r => r.id === id)
    if (index > -1) {
      // Use Vue.set for reactivity
      const updatedRoute = { ...state.routes[index], ...data }
      state.routes.splice(index, 1, updatedRoute)
    }
  },
  
  REMOVE_ROUTE(state, id) {
    state.routes = state.routes.filter(r => r.id !== id)
  },
  
  ADD_REQUEST_LOG(state, log) {
    state.requestLogs.unshift({
      ...log,
      id: `log_${Date.now()}`
    })
    if (state.requestLogs.length > state.maxLogs) {
      state.requestLogs = state.requestLogs.slice(0, state.maxLogs)
    }
  },
  
  CLEAR_REQUEST_LOGS(state) {
    state.requestLogs = []
  }
}

const actions = {
  async startServer({ state, commit }) {
    if (state.isRunning) return
    
    const result = await httpServer.start({
      port: state.port
    })
    
    if (result.success) {
      commit('SET_RUNNING', true)
      
      // Add all enabled routes to the server
      for (const route of state.routes.filter(r => r.enabled)) {
        const routeKey = `${route.method} ${route.path}`
        await httpServer.addRoute(routeKey, {
          status: route.status || 200,
          data: route.response || '{"message": "OK"}',
          headers: route.headers || '{"Content-Type": "application/json"}',
          delay: route.delay || 0
        })
      }
      
      // Setup request log listener
      httpServer.onRequestLog((log) => {
        commit('ADD_REQUEST_LOG', log)
      })
    }
    
    return result
  },
  
  async stopServer({ commit }) {
    const result = await httpServer.stop()
    if (result.success) {
      commit('SET_RUNNING', false)
    }
    return result
  },
  
  updatePort({ commit }, port) {
    commit('SET_PORT', port)
  },
  
  async addRoute({ commit, state }, route = {}) {
    const newRoute = {
      method: route.method || 'GET',
      path: route.path || `/api/endpoint-${Date.now()}`,
      status: route.status || 200,
      delay: route.delay || 0,
      response: route.response || '{"message": "Success", "data": null}',
      headers: route.headers || '{"Content-Type": "application/json"}',
      enabled: route.enabled !== undefined ? route.enabled : true,
      id: `route_${Date.now()}`,
      ...route
    }
    
    commit('ADD_ROUTE', newRoute)
    
    // If server is running, add the route immediately
    if (state.isRunning && newRoute.enabled) {
      const routeKey = `${newRoute.method} ${newRoute.path}`
      await httpServer.addRoute(routeKey, {
        status: newRoute.status,
        data: newRoute.response,
        headers: newRoute.headers,
        delay: newRoute.delay
      })
    }
    
    return newRoute
  },
  
  async updateRoute({ commit, state }, payload) {
    commit('UPDATE_ROUTE', payload)
    
    // If server is running, update the route on the server
    if (state.isRunning) {
      const route = state.routes.find(r => r.id === payload.id)
      if (route && route.enabled) {
        const routeKey = `${route.method} ${route.path}`
        await httpServer.addRoute(routeKey, {
          status: route.status,
          data: route.response,
          headers: route.headers,
          delay: route.delay
        })
      }
    }
  },
  
  async removeRoute({ commit, state }, id) {
    // Find the route to remove
    const route = state.routes.find(r => r.id === id)
    if (route && state.isRunning) {
      const routeKey = `${route.method} ${route.path}`
      await httpServer.removeRoute(routeKey)
    }
    commit('REMOVE_ROUTE', id)
  },
  
  clearRequestLogs({ commit }) {
    commit('CLEAR_REQUEST_LOGS')
  },
  
  applyConfig({ commit }, config) {
    if (config.port) commit('SET_PORT', config.port)
    if (config.routes) config.routes.forEach(route => commit('ADD_ROUTE', route))
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}